<template>
	<el-dialog
		:visible="showDialog"
		:append-to-body="true"
    :close-on-click-modal="false"
		title="真值反馈配置"
		width="850px"
		@close="dialogClose">
		<div class="position-relative">
			<el-button type="primary" size="small" class="mar-btm-10" @click="addLogicRule">新增规则配置</el-button>
			<i class="logic-rule-refresh-icon el-icon-refresh-right" @click="getLogicRuleList"></i>
			<el-tabs v-loading="tabLoading" v-model="activeLogics" class="mar-btm-20">
				<el-tab-pane v-for="tab in ruleTabData" :key="tab.value" :label="tab.label" :name="tab.value">
					<el-table :data="tab.data" border size="mini">
						<el-table-column prop="name" label="规则名称" show-overflow-tooltip></el-table-column>
            <el-table-column prop="lastUpdatedAt" width="150" label="更新时间" >
              <template slot-scope="scope">
                {{formatMeta(scope.row).lastUpdatedAtFromNow}}
                </template>
            </el-table-column>
						<el-table-column label="操作" width="240">
							<template slot-scope="scope">
								<el-button size="mini" @click="editLogicRule(scope.row)">编辑</el-button>
								<el-button size="mini" type="danger" @click="deleteLogicRule(scope.row)">删除</el-button>
								<el-button size="mini" type="primary" @click="cloneLogicRule(scope.row)">复制</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</div>
    <el-dialog
      :visible.sync="showLogicRuleDialog"
      :title="idEditRule ? '编辑规则配置' : '新增规则配置'"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="750px">
	    <IftttLogicForm
		    :rule-form="logicRuleForm"
		    @cancel="showLogicRuleDialog = false"
		    @confirm="submitLogicRule"></IftttLogicForm>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import {confirmHandle, formatHttpParams, messageHandle,formatMeta} from "@/utils";
	import IftttLogicForm from "@/page/IDE/editor/global/IftttLogicForm.vue";
  import {msgCode} from "@/config/string";
  import {mapActions} from "vuex";
	import API from "@/api";
  export default {
    name: "IftttLogic",
    components: {IftttLogicForm},
	  model: {
		  prop: 'showDialog',
		  event: 'change'
	  },
    props: {
	    editorType: {
		    type: String,
		    default: 'room', // room/component
	    },
	    showDialog: {
		    type: Boolean,
		    default: false,
	    },
      roomId: {
        type: String,
        default: '',
      },
      componentId: {
        type: String,
        default: '',
      },
      activeLogic: {
        type: String,
        default: 'room',
      },
    },
    data() {
      return {
        tabLoading: false,
        ruleTabData: [
          {
            label: '房间属性',
            value: 'room',
            data: []
          },
          {
            label: '设备状态',
            value: 'device',
            data: []
          },
          {
            label: '组件变量',
            value: 'widget',
            data: []
          },
          {
            label: '全局变量',
            value: 'global',
            data: []
          },
        ],
	      showLogicRuleDialog: false,
	      logicRuleFormLoading: false,
        logicRuleForm: {
          type: "",
          key: "",
          actions: [],
          name: '触发条件',
          npKeyIndex: 0,
          params: ''
        },
        tigerName: ["1"],
        currentWidgetId: "",
        idEditRule: false,
        activeNames: 0,
        activeLogics: 'room',
        formatMeta:formatMeta
      };
    },
    mounted() {
      this.getLogicRuleList();
	    this.$EventBus.$on('refreshGlobalLogicRules', this.getLogicRuleList);
    },
	  beforeDestroy() {
		  this.$EventBus.$off('refreshGlobalLogicRules');
	  },
    watch: {
      'activeLogic': {
        handler(val) {
          if (val) {
            this.activeLogics=val
          }
        },
        immediate: true,
        deep:true
      },
    },
    methods: {
      ...mapActions([
        'updateGlobalLogicList',
      ]),
      getLogicRuleList() {
        this.tabLoading = true;
        const assembleRuleData = (data = []) => {
          const roomRules = [];
          const deviceRules = [];
          const globalRules = [];
          const widgetRules = [];
          data.forEach(rule => {
            switch (rule.type) {
              case 'relatedSystem':
                roomRules.push(rule);
                break;
              case 'relatedDeviceStatus':
                deviceRules.push(rule);
                break;
              case 'relatedGlobal':
                globalRules.push(rule);
                break;
              case 'relatedAtomic':
	              widgetRules.push(rule);
                break;
              default:
                break;
            }
          });
					// TODO 不同类型的规则进行聚合处理
          this.ruleTabData[0].data = _.sortBy(roomRules, rule => rule.value);
          this.ruleTabData[1].data = _.sortBy(deviceRules, rule => rule.controlId);
          this.ruleTabData[2].data = widgetRules;
          this.ruleTabData[3].data = _.sortBy(globalRules, rule => rule.globalVar);
        };
	      switch (this.editorType) {
		      case 'room':
			      API.roomLogicRule.roomLogicRuleList({roomId: this.roomId}).then((resp) => {
				      this.tabLoading = false;
				      const {data = []} = resp;
				      assembleRuleData(data);
				      this.updateGlobalLogicList(data);
			      }).catch((err) => {
				      this.tabLoading = false;
				      console.log("err: ", err);
			      });
			      break;
		      case 'component':
			      API.componentLogicRule.componentLogicRuleList({componentId: this.componentId}).then((resp) => {
				      this.tabLoading = false;
				      const {data = []} = resp;
				      assembleRuleData(data);
				      this.updateGlobalLogicList(data);
			      }).catch((err) => {
				      this.tabLoading = false;
				      console.log("err: ", err);
			      });
			      break;
		      default:
			      break;
	      }
      },
      addLogicRule() {
        this.showLogicRuleDialog = true;
        this.idEditRule = false;
        this.logicRuleForm = {
          type: "",
          actions: [],
          npKeyIndex: 0,
          key: '',
          name: '触发条件',
          value: '',
          params: ''
        };
      },
	    editLogicRule(logicRule) {
        this.showLogicRuleDialog = true;
        this.logicRuleForm = _.cloneDeep(logicRule);
        this.idEditRule = true;
      },
	    deleteLogicRule(logicRule) {
	      const {_id, name = ''} = logicRule;
        confirmHandle({label: `确定要删除真值反馈规则：${name} 吗?`}).then(() => {
	        switch (this.editorType) {
		        case 'room':
			        API.roomLogicRule.roomLogicRuleDelete({_id}).then(result => {
				        messageHandle({code: msgCode.DELETE_SUCCESS, title: "真值反馈规则"});
				        this.getLogicRuleList();
			        });
			        break;
		        case 'component':
			        API.componentLogicRule.componentLogicRuleDelete({_id}).then(result => {
				        messageHandle({code: msgCode.DELETE_SUCCESS, title: "真值反馈规则"});
				        this.getLogicRuleList();
			        });
			        break;
		        default:
			        break;
	        }
        }).catch(() => {
        });
      },
	    cloneLogicRule(logicRule) {
        const params = {...logicRule, name: `${logicRule.name}-副本`};
        delete params._id;
		    switch (this.editorType) {
			    case 'room':
				    API.roomLogicRule.roomLogicRuleAdd(params).then(result => {
					    messageHandle({code: msgCode.COPY_SUCCESS, title: "真值反馈规则"});
					    this.getLogicRuleList();
				    }).catch((err) => {
				    });
				    break;
			    case 'component':
				    API.componentLogicRule.componentLogicRuleAdd(params).then(result => {
					    messageHandle({code: msgCode.COPY_SUCCESS, title: "真值反馈规则"});
					    this.getLogicRuleList();
				    }).catch((err) => {
				    });
				    break;
			    default:
				    break;
		    }
      },
      submitLogicRule() {
	      let api;
	      let title = '';
	      const code = !this.idEditRule ? msgCode.ADD_SUCCESS : msgCode.EDIT_SUCCESS;
	      const param = this.logicRuleForm;
	      switch (this.editorType) {
		      case 'room':
			      title = '房间真值反馈规则';
			      param.roomId = this.roomId;
			      api = !this.idEditRule ? API.roomLogicRule.roomLogicRuleAdd : API.roomLogicRule.roomLogicRuleEdit;
			      break;
		      case 'component':
			      title = '组件真值反馈规则';
			      param.componentId = this.componentId;
			      api = !this.idEditRule ? API.componentLogicRule.componentLogicRuleAdd : API.componentLogicRule.componentLogicRuleEdit;
			      break;
		      default:
			      break;
	      }
	      this.logicRuleFormLoading = true;
	      api(formatHttpParams(param)).then(result => {
		      messageHandle({code: code, title: title});
		      this.showLogicRuleDialog = false;
		      this.logicRuleFormLoading = false;
		      this.getLogicRuleList();
	      }).catch(err => {
		      console.log('err', err);
		      this.logicRuleFormLoading = false;
	      });
      },
	    dialogClose() {
		    this.$emit('change', false);
	    }
    },
  };
</script>

<style lang="less" scoped>

	.logic-rule-refresh-icon {
		position: absolute;
		right: 0;
		top: 52px;
		font-size: 20px;
		cursor: pointer;
		z-index: 99;

		&:hover {
			color: @colorPrimary;
			font-weight: bold;
		}
	}

</style>
